package com.szgz.platform.controller;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.PullImageResultCallback;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient;
import com.szgz.platform.result.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Web终端Docker容器管理控制器
 * 提供容器创建、启动、停止、删除等API
 */
@RestController
@RequestMapping("/api/terminal")
@CrossOrigin(origins = "*")
public class WebTerminalController {

    private static final Logger logger = LoggerFactory.getLogger(WebTerminalController.class);
    private final DockerClient dockerClient;

    public WebTerminalController() {
        // 初始化Docker客户端，使用Apache HttpClient传输方式
        DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost("tcp://192.168.1.168:2376")
                .build();
        // 使用Apache HttpClient替代Jersey
        DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
                .dockerHost(config.getDockerHost())
                .sslConfig(config.getSSLConfig())
                .build();

        this.dockerClient = DockerClientBuilder.getInstance(config)
                .withDockerHttpClient(httpClient)
                .build();
    }

    /**
     * 创建并启动Linux容器用于Web终端
     */
    @PostMapping("/container/create")
    public ApiResponse<Map<String, String>> createContainer(@RequestParam(defaultValue = "ubuntu:latest") String image) {
        try {
            // 拉取镜像（如果不存在）
            try {
                dockerClient.pullImageCmd(image)
                    .exec(new PullImageResultCallback())
                    .awaitCompletion();
            } catch (Exception e) {
                logger.warn("拉取镜像失败，尝试使用本地镜像: {}", e.getMessage());
            }

            // 创建容器配置
            CreateContainerResponse container = dockerClient.createContainerCmd(image)
                    .withName("web-terminal-" + System.currentTimeMillis())
                    .withTty(true)
                    .withStdinOpen(true)
                    .withCmd("/bin/bash")
                    .withExposedPorts(ExposedPort.tcp(22)) // SSH端口
                    .withPortBindings(new PortBinding(Ports.Binding.bindPort(0), ExposedPort.tcp(22)))
                    .exec();

            // 启动容器
            dockerClient.startContainerCmd(container.getId()).exec();

            // 获取容器信息
            InspectContainerResponse containerInfo = dockerClient.inspectContainerCmd(container.getId()).exec();
            
            Map<String, String> result = new HashMap<>();
            result.put("containerId", container.getId());
            result.put("containerName", containerInfo.getName());
            result.put("status", "running");
            result.put("image", image);

            logger.info("容器创建成功: {}", container.getId());
            return ApiResponse.success(result);

        } catch (Exception e) {
            logger.error("创建容器失败", e);
            return ApiResponse.fail("创建容器失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有容器列表
     */
    @GetMapping("/containers")
    public ApiResponse<List<Map<String, Object>>> listContainers() {
        try {
            List<Container> containers = dockerClient.listContainersCmd()
                    .withShowAll(true)
                    .exec();

            List<Map<String, Object>> result = containers.stream()
                    .filter(container -> container.getNames()[0].contains("web-terminal"))
                    .map(container -> {
                        Map<String, Object> containerInfo = new HashMap<>();
                        containerInfo.put("id", container.getId());
                        containerInfo.put("name", container.getNames()[0]);
                        containerInfo.put("image", container.getImage());
                        containerInfo.put("status", container.getStatus());
                        containerInfo.put("state", container.getState());
                        containerInfo.put("created", container.getCreated());
                        return containerInfo;
                    })
                    .collect(Collectors.toList());

            return ApiResponse.success(result);

        } catch (Exception e) {
            logger.error("获取容器列表失败", e);
            return ApiResponse.fail("获取容器列表失败: " + e.getMessage());
        }
    }

    /**
     * 启动容器
     */
    @PostMapping("/container/{containerId}/start")
    public ApiResponse<String> startContainer(@PathVariable String containerId) {
        try {
            dockerClient.startContainerCmd(containerId).exec();
            logger.info("容器启动成功: {}", containerId);
            return ApiResponse.success("容器启动成功");
        } catch (Exception e) {
            logger.error("启动容器失败: {}", containerId, e);
            return ApiResponse.fail("启动容器失败: " + e.getMessage());
        }
    }

    /**
     * 停止容器
     */
    @PostMapping("/container/{containerId}/stop")
    public ApiResponse<String> stopContainer(@PathVariable String containerId) {
        try {
            dockerClient.stopContainerCmd(containerId).exec();
            logger.info("容器停止成功: {}", containerId);
            return ApiResponse.success("容器停止成功");
        } catch (Exception e) {
            logger.error("停止容器失败: {}", containerId, e);
            return ApiResponse.fail("停止容器失败: " + e.getMessage());
        }
    }

    /**
     * 删除容器
     */
    @DeleteMapping("/container/{containerId}")
    public ApiResponse<String> removeContainer(@PathVariable String containerId) {
        try {
            // 先停止容器
            try {
                dockerClient.stopContainerCmd(containerId).exec();
            } catch (Exception e) {
                logger.warn("停止容器时出现异常（可能已停止）: {}", e.getMessage());
            }

            // 删除容器
            dockerClient.removeContainerCmd(containerId).exec();
            logger.info("容器删除成功: {}", containerId);
            return ApiResponse.success("容器删除成功");
        } catch (Exception e) {
            logger.error("删除容器失败: {}", containerId, e);
            return ApiResponse.fail("删除容器失败: " + e.getMessage());
        }
    }

    /**
     * 获取容器详细信息
     */
    @GetMapping("/container/{containerId}")
    public ApiResponse<Map<String, Object>> getContainerInfo(@PathVariable String containerId) {
        try {
            InspectContainerResponse containerInfo = dockerClient.inspectContainerCmd(containerId).exec();
            
            Map<String, Object> result = new HashMap<>();
            result.put("id", containerInfo.getId());
            result.put("name", containerInfo.getName());
            result.put("image", containerInfo.getConfig().getImage());
            result.put("status", containerInfo.getState().getStatus());
            result.put("running", containerInfo.getState().getRunning());
            result.put("created", containerInfo.getCreated());
            result.put("ports", containerInfo.getNetworkSettings().getPorts());

            return ApiResponse.success(result);

        } catch (Exception e) {
            logger.error("获取容器信息失败: {}", containerId, e);
            return ApiResponse.fail("获取容器信息失败: " + e.getMessage());
        }
    }
}